package org.abettor.nookinfo.wiki;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.modal.WikiTerm;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 获取最近更新的百科条目
 * @author shawn
 *
 */
public class RecentTerms extends Activity
{
	private static final int REFRESHED = 1;//菜单更新已完成事件
	private static final int FAILED = 2;//菜单更新失败时间
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private YoumiManager youmi = new YoumiManager(this);
	private int page = 1;
	private List<WikiTerm> termList = new ArrayList<WikiTerm>();
	private ProgressDialog progressDialog = null;//进度条对话框
	private Worker worker = null;//网络访问线程
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				LinearLayout layout = (LinearLayout) findViewById(R.id.wikiRecentLayout);
				layout.removeAllViews();
				for(WikiTerm term : termList)
				{
					//	依次绘制百科条目
					final WikiTerm theTerm = term;
					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0f);
					params.gravity = 0x30;
					LinearLayout item = new LinearLayout(RecentTerms.this);
					item.setOrientation(LinearLayout.VERTICAL);
					item.setLayoutParams(params);
					layout.addView(item);

					//	词条名称
					TextView title = new TextView(RecentTerms.this);
					title.setText(theTerm.name);
					title.setClickable(true);
					title.setGravity(0x03 | 0x30);
					title.setTextColor(Color.BLACK);
					title.setBackgroundColor(0x88888888);
					title.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
					title.setTextSize(18f);
					title.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View view)
						{
							//	进入百科内容页面
							Bundle extras = new Bundle();
							extras.putInt(WikiContent.WIKI_CONTENT_ID, theTerm.id);
							extras.putString(WikiContent.WIKI_CONTENT_NAME, theTerm.name);
							Intent contentIntent = new Intent();
							contentIntent.setClass(RecentTerms.this, WikiContent.class);
							contentIntent.putExtras(extras);
							startActivity(contentIntent);
						}
					});
					item.addView(title);

					//	更新时间
					TextView update = new TextView(RecentTerms.this);
					update.setText(sdf.format(theTerm.update));
					update.setGravity(0x03 | 0x30);
					update.setTextColor(Color.BLACK);
					update.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
					item.addView(update);

					//	摘要
					TextView summary = new TextView(RecentTerms.this);
					summary.setText(theTerm.content.trim());
					summary.setGravity(0x03 | 0x30);
					summary.setTextColor(0xAA000000);
					item.addView(summary);
				}
				ScrollView scroll = (ScrollView) findViewById(R.id.wikiRecentScroll);
				scroll.scrollTo(0, 0);

				//	按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if(val < 20)
				{
					youmi.showYoumi(YoumiManager.Position.bottom, Color.WHITE, Color.BLACK, 0xAA);
				}
			}
			else if(msg.what == FAILED)
			{
				Builder builder = new Builder(RecentTerms.this);
				builder.setTitle(R.string.wiki_recent_terms_fail_title);
				builder.setMessage(R.string.wiki_recent_terms_fail_content);
				builder.setPositiveButton(R.string.wiki_recent_terms_fail_btn_ok, new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialoginterface, int i)
					{
						dialoginterface.dismiss();
					}
				});
				builder.show();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wiki_recent_terms);
		onRefreshClicked(null);
	}

	/**
	 * “搜索”按钮事件方法
	 * @param v
	 */
	public void onSearchClicked(View v)
	{
		//	显示搜索界面
		Intent search = new Intent();
		search.setClass(this, WikiSearch.class);
		startActivity(search);
	}

	/**
	 * “刷新”按钮事件方法
	 * @param v
	 */
	public void onRefreshClicked(View v)
	{
		termList.clear();
		worker = new Worker();
		worker.start();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setTitle(R.string.wiki_recent_terms_progress_title);
		progressDialog.setMessage(getText(R.string.wiki_recent_terms_progress_content));
		progressDialog.setButton(getText(R.string.wiki_recent_terms_progress_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialoginterface, int i)
			{
				worker.kill();
			}
		});
		progressDialog.show();
		synchronized (worker)
		{
			worker.notify();
		}
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onRetrunClicked(View v)
	{
		finish();
	}

	/**
	 * “上一页”按钮事件方法
	 * @param v
	 */
	public void onPrevClicked(View v)
	{
		if(page <= 1)
		{
			return;
		}

		page --;
		onRefreshClicked(v);
	}

	/**
	 * “下一页”按钮事件方法
	 * @param v
	 */
	public void onNextClicked(View v)
	{
		page ++;
		onRefreshClicked(v);
	}

	/**
	 * 读取最近更新的百科列表的工作线程类
	 * @author abettor
	 *
	 */
	private class Worker extends Thread
	{
		//	线程是否为意外退出的标记
		private boolean cancel = false;

		/**
		 * 强制杀死工作者线程
		 */
		public void kill()
		{
			cancel = true;
			this.interrupt();
		}

		@Override
		public void run()
		{
			try
			{
				//	等待对话框创建完成
				synchronized (this)
				{
					wait();
				}

				//	此处访问网络并获取列表
				fetchLists(termList);

				//	关闭进度对话框并通知界面更新
				progressDialog.dismiss();
				if(! cancel)
				{
					//	在非意外中断情况下才更新界面
					Message msg = new Message();
					msg.what = REFRESHED;
					handler.sendMessage(msg);
				}
				else
				{
					//	意外中断的情况下，显示错误对话框
					Message msg = new Message();
					msg.what = FAILED;
					handler.sendMessage(msg);
				}
			}
			catch (Exception e)
			{
				//	清除列表
				try { progressDialog.dismiss(); } catch (Exception ex) { };
				termList.clear();
				//	意外中断的情况下，显示错误对话框
				Message msg = new Message();
				msg.what = FAILED;
				handler.sendMessage(msg);
				Log.d(this.getClass().getName(), "", e);
			}
		}

		//	读取列表
		private void fetchLists(List<WikiTerm> termList) throws Exception
		{
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			String url = AddressConstant.WIKI_RECENT.replace("PAGE", page + "");
			Document doc = db.parse(url);
			NodeList list = doc.getElementsByTagName("term");
			int len = list.getLength();
			for(int i = 0; i < len; i ++)
			{
				WikiTerm term = new WikiTerm();
				Node node = list.item(i);
				NodeList nodes = node.getChildNodes();
				int count = nodes.getLength();
				for(int j = 0; j < count; j ++)
				{
					Node termNode = nodes.item(j);
					String nodeName = termNode.getNodeName();
					if("id".equals(nodeName))
					{
						String id = termNode.getTextContent();
						term.id = Integer.valueOf(id);
					}
					else if("name".equals(nodeName))
					{
						term.name = termNode.getTextContent();
					}
					else if("update".equals(nodeName))
					{
						String update = termNode.getTextContent();
						term.update = sdf.parse(update);
					}
					else if("summary".equals(nodeName))
					{
						term.content = "";
						NodeList summaryNodes = termNode.getChildNodes();
						int size = summaryNodes.getLength();
						for(int k = 0; k < size; k ++)
						{
							Node summary = summaryNodes.item(k);
							if(summary instanceof CDATASection)
							{
								CDATASection cdata = (CDATASection) summary;
								term.content = cdata.getData();
								break;
							}
						}
					}
				}
				termList.add(term);
			}

			list = doc.getElementsByTagName("page");
			String pageNo = list.item(0).getTextContent();
			page = Integer.parseInt(pageNo);
		}
	}
}
